最近刚好有个功能,需要这个逻辑,话不多说,上代码。
struct handle_data {
unsigned long process_id;
HWND best_handle;
};
BOOL IsMainWindow(HWND handle)
{
return GetWindow(handle, GW_OWNER) == (HWND)0 && IsWindowVisible(handle);
}
HWND FindMainWindow(unsigned long process_id)
{
handle_data data;
data.process_id = process_id;
data.best_handle = 0;
EnumWindows(EnumWindowsCallback, (LPARAM)&data);
return data.best_handle;
}
BOOL CALLBACK EnumWindowsCallback(HWND handle, LPARAM lParam)
{
handle_data& data = *(handle_data*)lParam;
unsigned long process_id = 0;
GetWindowThreadProcessId(handle, &process_id);
if (data.process_id != process_id || !IsMainWindow(handle)) {
return TRUE;
}
data.best_handle = handle;
return FALSE;
}
然后main函数,这样调用即可,
HWND hwnd = FindMainWindow(uProcessID);
这个uProcessID就是任务管理器里PID一列的内容,你也可以写个函数用进程名来获取。